/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/

const PENGDING = 'pengding'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class myPromise {
    constructor (executor) {
        // 捕获错误
        try {
            executor(this.resolve, this.reject);
        } catch (e) {
            this.reject(e)
        }
        // 接收到executor执行器，立即执行
    }
    status = PENGDING;
    // 成功之后的值，实例属性
    value = undefined;
    // 失败之后的值
    reason = undefined;
    // 成功回调
    successCallback = []
    // 失败回调
    failCallback = []
    resolve = value => {
        if (this.status !== PENGDING) return;
        this.status = FULFILLED;
        // 保存成功之后的值
        this.value = value;
        // 判断成功回调是否存在 如果存在 调用
        // this.successCallback && this.successCallback(this.value)
        while(this.successCallback.length) {
            this.successCallback.shift()(this.value)
        }
    }
    reject = reason => {
        if (this.status !== PENGDING) return;
        this.status = REJECTED;
        // 保存失败之后的值
        this.reason = reason;
        // 判断失败回调是否存在 如果存在 调用
        // this.failCallback && this.failCallback(this.reason)
        while(this.failCallback.length) {
            this.failCallback.shift()(this.reason)
        }
    }
    then (successCallback, failCallback) {
        // 判断是否有函数
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => { throw reason }
        let promise2 = new myPromise((resolve, reject) => {
            // 判断状态
            if (this.status === FULFILLED) {
                // 捕获错误
                setTimeout(() => {
                    try {
                        let x = successCallback(this.value)
                            // 判断x 的值是普通值还是promise 对象
                            // 如果是普通值 直接调用resolve
                            // 如果是promise 对象 查看promise对象返回的结果
                            // 再根据promise 对象放回的结果 决定调用resolve还是调用reject
                        resolvePromise(promise2, x, resolve, reject)
                    } catch(e) {
                        reject(e)
                    }  
                }, 0)
                // resolve(x);
            } else if (this.status === REJECTED) {
                // 捕获错误
                setTimeout(() => {
                    try {
                        let x = failCallback(this.reason)
                            // 判断x 的值是普通值还是promise 对象
                            // 如果是普通值 直接调用resolve
                            // 如果是promise 对象 查看promise对象返回的结果
                            // 再根据promise 对象放回的结果 决定调用resolve还是调用reject
                        resolvePromise(promise2, x, resolve, reject)
                    } catch(e) {
                        reject(e)
                    }  
                }, 0)
            } else {
                // 等待
                // 成功回调和失败回调存起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value)
                                // 判断x 的值是普通值还是promise 对象
                                // 如果是普通值 直接调用resolve
                                // 如果是promise 对象 查看promise对象返回的结果
                                // 再根据promise 对象放回的结果 决定调用resolve还是调用reject
                                resolvePromise(promise2, x, resolve, reject)
                        } catch(e) {
                            reject(e)
                        }  
                    }, 0)
                });
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason)
                                // 判断x 的值是普通值还是promise 对象
                                // 如果是普通值 直接调用resolve
                                // 如果是promise 对象 查看promise对象返回的结果
                                // 再根据promise 对象放回的结果 决定调用resolve还是调用reject
                                resolvePromise(promise2, x, resolve, reject)
                            
                        } catch(e) {
                            reject(e)
                        }  
                    }, 0)
                });
            }
        });
        return promise2;
    }
    finally (callback) {
        return this.then(value => {
            // 将callback结果转成promise并执行
            return myPromise.resolve(callback()).then(() => value)
        }, reason => {
            return myPromise.resolve(callback()).then(() => { throw reason })
        })
    }
    catch (failCallback) {
        return this.then(undefined, failCallback)
    }
    static resolve (value) {
        if (value instanceof myPromise) {
            return value
        } else {
            return new myPromise((resolve, reject) => {
                resolve(value)
            })
        }
    }
    static all (array) {
        let result = [];
        let index = 0;
        return new myPromise((resolve, reject) => {
            function addData (key, value) {
                result[key] = value;
                index++;
                if (index === array.length) {
                    // 判断是否等于长度，执行完毕
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof myPromise) {
                    // promise 对象
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    // 普通值
                    addData(i, array[i])
                }
            }
        })
    }
}

function resolvePromise (promise2, x, resolve, reject) {
    // 判断x是不是myPromise上的实例
    // instanceof 运算符用于检测构造函数的 prototype 
    // 属性是否出现在某个实例对象的原型链上。
    if (promise2 === x) {
        // 判断是不是调用了自己
        reject(new TypeError('Chaining cycle detected for promise #'))
    }
    if (x instanceof myPromise) {
        // promise 对象
        // x.then(value => resolve(value), reason => reject(reason))
        x.then(resolve, reject)
    } else {
        // 普通值
        resolve(x);
    }
}

module.exports = myPromise